package cc.sunni.files.service.impl;

import cc.sunni.common.utils.extend.AliImageReviewUtils;
import cc.sunni.common.utils.extend.AliyunResource;
import cc.sunni.files.resource.FileResource;
import cc.sunni.files.service.UploaderService;
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class UploaderServiceImpl implements UploaderService {
    @Autowired
    public FileResource fileResource;
    @Autowired
    public AliyunResource aliyunResource;
    @Autowired
    private AliImageReviewUtils aliImageReviewUtils;

    @Override
    public String uploadOSS(MultipartFile file) throws Exception {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = fileResource.getEndpoint();
        // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = aliyunResource.getAccessKeyID();
        String accessKeySecret = aliyunResource.getAccessKeySecret();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //构建日期路径：avatar/2019/02/26/文件名
        String filePath = new DateTime().toString("yyyy/MM/dd");

        String objectName = fileResource.getObjectName();
        //文件名：uuid.扩展名
        String original = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString();
        String suffix = original.substring(original.lastIndexOf("."));
        String newName = fileName + suffix;
        String fileUrl = objectName + "/" + filePath + "/" + newName;

        // 上传网络流。
        InputStream inputStream = file.getInputStream();
        ossClient.putObject(fileResource.getBucketName(), fileUrl, inputStream);

        // 关闭OSSClient。
        ossClient.shutdown();

        //获取url地址
        return "https://" + fileResource.getBucketName() + "." + endpoint + "/" + fileUrl;
        // 可以调用doAliImageReview方法审核图片
    }

    // 图片审核失败后的默认图片
    public static final String FAILED_IMAGE_URL = "https://imooc-news.oss-cn-shanghai.aliyuncs.com/image/faild.jpeg";
    private String doAliImageReview(String pendingImageUrl) {
        boolean result = false;
        try {
            result = aliImageReviewUtils.reviewImage(pendingImageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (!result) {
            return FAILED_IMAGE_URL;
        }
        return pendingImageUrl;
    }
}
